package com.hxl.alert.client;

import com.hxl.alert.constant.MisfireStrategyEnum;
import com.hxl.alert.entity.XxlJobInfo;
import com.xxl.job.core.enums.ExecutorBlockStrategyEnum;
import com.xxl.job.core.glue.GlueTypeEnum;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.util.*;

@Component
public class XxlJobApiClient {

    @Value("${xxl.job.admin.addresses}")
    private String adminUrl;

    @Value("${xxl.job.accessToken}")
    private String accessToken;

    private final String cookie = "XXL_JOB_LOGIN_IDENTITY=7b226964223a312c22757365726e616d65223a2261646d696e222c2270617373776f7264223a226531306164633339343962613539616262653536653035376632306638383365222c22726f6c65223a312c227065726d697373696f6e223a6e756c6c7d";

    private final RestTemplate restTemplate = new RestTemplate();

    public void createJob(XxlJobInfo jobInfo) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        if (StringUtils.hasText(accessToken)) {
            headers.set("XXL-JOB-ACCESS-TOKEN", accessToken);
            headers.set("Cookie", cookie);
        }
        jobInfo.setTriggerStatus(1);
        jobInfo.setJobDesc("越限告警定时任务" + jobInfo.getExecutorParam());
        jobInfo.setAuthor("hxl");
        jobInfo.setGlueType(GlueTypeEnum.BEAN.getDesc());
        jobInfo.setMisfireStrategy(MisfireStrategyEnum.FIRE_ONCE_NOW.name());
        jobInfo.setExecutorRouteStrategy("FIRST");
        jobInfo.setExecutorBlockStrategy(ExecutorBlockStrategyEnum.SERIAL_EXECUTION.name());
        // 创建HttpEntity，包含请求体和请求头
        HttpEntity<XxlJobInfo> requestEntity = new HttpEntity<>(jobInfo, headers);

        // 发送POST请求，指定目标URL，传递请求实体

        ResponseEntity<String> response = restTemplate.exchange(adminUrl + "/jobinfo/add", HttpMethod.POST, requestEntity, String.class);
//        Map<String, Object> request = new HashMap<>();
//        request.put("jobGroup", jobInfo.getJobGroup());
//        request.put("scheduleType", jobInfo.getScheduleType());
//        request.put("scheduleConf", jobInfo.getScheduleConf());
//        request.put("executorHandler", jobInfo.getExecutorHandler());
//        request.put("executorParam", jobInfo.getExecutorParam());
//        request.put("triggerStatus", 1); // 启用任务

//        ResponseEntity<Map> response = restTemplate.postForEntity(
//                adminUrl + "/jobinfo/add",
//                new HttpEntity<>(request, headers),
//                Map.class
//        );

        if (!response.getStatusCode().is2xxSuccessful()) {
            throw new RuntimeException("创建任务失败: " + response.getBody());
        }
    }

    /**
     * 根据任务参数（executorParam）查询任务ID列表
     */
    public void findJobIdsAndStopJobByParam(String executorParam) {
        List<Integer> jobIds = new ArrayList<>();
        int page = 0;
        int pageSize = 100; // 分页大小（根据XXL-Job Admin配置调整）

        while (true) {
            // 1. 调用分页查询接口
            Map<String, Object> response = queryJobsByPage(page, pageSize, executorParam);
            if (response == null) break;

            // 2. 解析任务ID
            List<Map<String, Object>> jobs = (List<Map<String, Object>>) response.get("data");
            if (jobs == null || jobs.isEmpty()) break;

            jobs.forEach(job -> {
                Integer id = (Integer) job.get("id");
                String param = (String) job.get("executorParam");
                if (executorParam.equals(param)) {
                    jobIds.add(id);
                }
            });

            // 3. 判断是否还有下一页
            Integer total = (Integer) response.get("recordsTotal");
            if ((page + 1) * pageSize >= total) break;
            page++;
        }

        jobIds.forEach(this::stopJob);
    }

    /**
     * 分页查询任务列表
     */
    private Map<String, Object> queryJobsByPage(int page, int pageSize, String executorParam) {
        try {
            HttpHeaders headers = new HttpHeaders();
//            headers.setContentType(MediaType.MULTIPART_FORM_DATA);
            if (StringUtils.hasText(accessToken)) {
                headers.set("XXL-JOB-ACCESS-TOKEN", accessToken);
                headers.set("Cookie", cookie);
            }

//            // 构造查询条件（按需添加其他过滤字段）
//            Map<String, Object> request = new HashMap<>();
//            request.put("start", page * pageSize);
//            request.put("length", pageSize);
//            request.put("jobGroup", 2); // 默认当前组
//            request.put("triggerStatus", -1); // 默认调度状态：0-停止，1-运行 -1全部
//            request.put("executorParam", executorParam); // 按参数过滤
// 构建请求参数
            UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(adminUrl + "/jobinfo/pageList")
                    .queryParam("start", page * pageSize) // 可选参数，默认值为 0
                    .queryParam("length", pageSize)     // 可选参数，默认值为 10
                    .queryParam("jobGroup", 2)          // 可选参数，根据实际情况传入
                    .queryParam("triggerStatus", -1)    // 可选参数，根据实际情况传入
                    .queryParam("executorParam", executorParam);
            HttpEntity<String> entity = new HttpEntity<>(headers);
            ResponseEntity<Map> response = restTemplate.exchange(
                    builder.toUriString(),  // 完整的 URL
                    HttpMethod.GET,  // 请求方法
                    entity,  // 请求头
                    Map.class  // 响应类型
            );

            if (response.getStatusCode() == HttpStatus.OK) {
                return response.getBody();
            }
        } catch (Exception e) {
            // 记录日志或抛出自定义异常
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 终止单个任务
     */
    private void stopJob(Integer jobId) {
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            if (StringUtils.hasText(accessToken)) {
                headers.set("XXL-JOB-ACCESS-TOKEN", accessToken);
                headers.set("Cookie", cookie);
            }

            Map<String, Object> request = new HashMap<>();
            request.put("id", jobId);

            UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(adminUrl + "/jobinfo/stop")
                    .queryParam("id", jobId);
            HttpEntity<String> entity = new HttpEntity<>(headers);
            ResponseEntity<Map> response = restTemplate.exchange(
                    builder.toUriString(),  // 完整的 URL
                    HttpMethod.DELETE,  // 请求方法
                    entity,  // 请求头
                    Map.class  // 响应类型
            );
            if (response.getStatusCode() == HttpStatus.OK) {
                return ;
            }
        } catch (Exception e) {
            // 记录日志或抛出自定义异常
            e.printStackTrace();
        }
    }
}